package com.cgs.query.service.jpa

import com.cgs.query.domain.QuerySource
import com.cgs.query.exception.QueryException
import org.springframework.data.jpa.repository.JpaRepository
import org.springframework.data.jpa.repository.Query

interface QuerySourceRepository : JpaRepository<QuerySource, String> {

    @Query("select s.* from query_source s , query_project p where s.id = p.source_id and p.name = ?1", nativeQuery = true)
    fun findByProjectName(name: String): QuerySource?

    @Query("select s.* from query_source s , query_project p where s.id = p.source_id and p.name = ?1", nativeQuery = true)
    fun findByDefineNameAndProjectName(name: String): QuerySource?

    @Query("select new com.cgs.query.service.jpa.SourceIdPO(pd.sourceId,qp.sourceId) from QueryDefine qd, QueryProject qp, Project2Define pd " +
            "where qp.name = pd.projectName and pd.defineId = qd.id and qd.name = ?1 and pd.alias =?2 and pd.projectName=?3")
    fun findSourceIdPODtoByDefineNameAndAliasAndProjectName(defineName: String, alias: String, projectName: String): SourceIdPO?

    @Query("select qs from QuerySource qs where qs.id not in(select qp.sourceId from QueryProject qp where qp.lockType = 'LOCK_UN_RUN')")
    fun findByUnLock(): List<QuerySource>?

    @Query("select qs from QuerySource qs where qs.id not in(select qp.sourceId from QueryProject qp where qp.lockType = 'LOCK_UN_RUN' and qp.name != ?1) ")
    fun findByUnLockAndProjectName(projectName: String?): List<QuerySource>?

}

/**
 * 数据源对象
 * dSourceId： Project2Define 数据源id
 * pSourceId： Project 数据源id
 */
class SourceIdPO(private val dSourceId: String?,
                 private val pSourceId: String?) {

    fun getSourceId(): String? {
        return if (dSourceId.isNullOrBlank()) {
            pSourceId
        } else {
            dSourceId
        }
    }
}